<template>
  <div>
    <!-- 基础信息卡片 -->
    <el-card class="m-btm">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
        </div>
      </template>
      <!-- 表单区域 -->
      <el-form label-position="top" :size="size" :model="form">
        <el-row :gutter="24" justify="space-between">
          <!-- 遍历表单配置项 -->
          <template v-for="item in formConfig" :key="item.field">
            <!-- 根据 showIf 条件决定是否显示该列 -->
            <el-col
              v-if="!item.showIf || item.showIf(form)"
              :span="item.colSpan || 5"
            >
              <el-form-item
                :label="item.label"
                :prop="item.field"
                :required="item.required"
              >
                <!-- input 输入框 -->
                <el-input
                  v-if="item.component === 'input'"
                  v-model="form[item.field]"
                  :placeholder="`请输入${item.label}`"
                  :type="item.inputType || 'text'"
                />

                <!-- number 输入框 -->
                <!-- <el-input-number
                  v-else-if="item.component === 'number'"
                  v-model="form[item.field]"
                  :placeholder="`请输入${item.label}`"
                  style="width: 100%"
                /> -->

                <!-- select 下拉框 -->
                <el-select
                  v-else-if="item.component === 'select'"
                  v-model="form[item.field]"
                  :placeholder="`请选择${item.label}`"
                  :clearable="true"
                  @change="
                    item.events?.change &&
                      item.events.change(form[item.field], form)
                  "
                >
                  <!-- 遍历选项数据 -->
                  <el-option
                    v-for="opt in optionsMap[item.optionsKey]"
                    :key="opt.value || opt.id"
                    :label="opt.label || opt.title || opt.name"
                    :value="opt.value || opt.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </template>

          <!-- 占位空列（保持布局对齐） -->
          <el-col :span="5"></el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 包含表格的卡片 -->
    <el-card class="m-btm demo-tabs">
      <!-- 使用 VXE-Tabs 组件 -->
    <el-tabs v-model="activeName" class="demo-tabs" >
        <!-- 实体类字段标签页 -->
        <el-tab-pane label="实体类字段" name="1">
          <!-- 使用 VXE-Grid 组件展示表格数据 -->
          <vxe-grid v-bind="gridOptions1">
            <template #operate="{ row, rowIndex }">
              <vxe-button mode="text" status="error"  icon="vxe-icon-delete" content="删除" @click="deleteRow(row)"></vxe-button>
            </template>

            <template #toolbar_buttons>
              <vxe-button size="mini" status="primary" @click="addRow"  icon="vxe-icon-add" content="新增行"></vxe-button>
            </template>
          </vxe-grid>
        </el-tab-pane>
        <!-- 下游单据标签页 -->
        <el-tab-pane label="下游单据" name="2">
          <vxe-grid v-bind="gridOptions2">
            <template #operate_down="{ row }">
              <vxe-button mode="text" status="error" content="删除" icon="vxe-icon-delete"  @click="deleteDownRow(row)"
                ></vxe-button
              >
            </template>

            <template #toolbar>
              <vxe-toolbar>
                <template #buttons>
                  <vxe-button
                    @click="addDownRow"  status="primary"
                    size="mini"  icon="vxe-icon-add" content="新增行"
                    ></vxe-button
                  >
                </template>
                <template #tools>
                </template>
              </vxe-toolbar>
            </template>
          </vxe-grid>
        </el-tab-pane>

        <!-- 关联单据标签页 -->
        <el-tab-pane label="关联单据" name="3">
          <vxe-grid v-bind="gridOptions3">
            <template #operate_join="{ row }">
              <vxe-button mode="text" status="error" content="删除" icon="vxe-icon-delete" @click="deleteJoinRow(row)"
                ></vxe-button
              >
            </template>
            <template #toolbar>
              <vxe-toolbar>
                <template #buttons>
                  <vxe-button status="primary"
                    @click="addJoinRow"
                    size="mini"  icon="vxe-icon-add" content="新增行"
                    ></vxe-button
                  >
                </template>
              </vxe-toolbar>
            </template>
          </vxe-grid>
        </el-tab-pane>
      </el-tabs>
      <!-- 新增/编辑弹窗组件 -->
      <FieldConfigDialog @save="onSave" ref="fieldDialog" />
    </el-card>
    <!-- 底部提交按钮卡片 -->
    <el-card class="card-e">
      <div class="submit-flex-e">
        <vxe-button status="primary" @click="submitForm" size="mini" content="提交"></vxe-button>
        <vxe-button @click="goBack" content="返回" size="mini"></vxe-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
// 导入必要的 Vue 3 Composition API 和类型
import { ref, onMounted, reactive, watch } from "vue";
import type { VxeGridProps, VxeGridInstance } from "vxe-table";
import { useRoute ,useRouter} from "vue-router";
// 导入相关的 API 函数
import {
  queryList,
  sysDict,
  getBaseField,
  formAdd,
  checkOnly,
  getFormDetail,
} from "@/api";
// 导入自定义的弹窗组件
import FieldConfigDialog from "@/components/FieldConfigDialog.vue";
import type { ComponentSize } from "element-plus";
import type { VxeTabsPropTypes } from "vxe-pc-ui";
const size = ref<ComponentSize>("small");
const mini = ref<VxeTabsPropTypes.Size>('mini')
// 获取当前路由对象
const route = useRoute();
const router = useRouter();
const activeName = ref('1')
// 定义字段与其对应中文标题的映射关系
const fieldLabelMap = {
  title: "显示名称",
  field: "字段英文名称",
  width: "表格宽度",
  isTable: "是否表格显示",
  isForm: "是否表单显示",
  isSearch: "是否查询",
  fieldType: "字段类型",
  formType: "表单类型",
  fieldLength: "数据表字段长度",
  formRequire: "表单是否必填",
  exportExcel: "是否导出",
  importExcel: "是否导入",
  isSort: "是否排序",
  dictType: "字典类型",
  isTableEdit: "是否表格编辑",
  isFormEdit: "是否表单编辑",
  isTotal: "是否合计",
  sort: "排序",
  tableAlias: "关联表别名",
  tableField: "关联表字段",
  searchCondition: "查询条件",
  searchValue: "查询值",
  isUnique: "是否唯一",
  selClassName: "选择类名称",
  selField: "选择类字段",
};

// 响应式变量，用于存储所有选项数据
const optionsMap = ref({
  getOptions: [], // 表单类型选项
  InheritOptions: [], // 继承类选项
  sortTypeOptions: [], // 排序类型选项
  isOrNotOptions: [], // 是/否选项
  menuList: [], // 菜单列表
});

// 异步获取所有字典和列表数据
const getDatas = async () => {
  // 获取表单类型字典
  const dictSelect = await sysDict({ field: "type", value: "form_form_type" });
  optionsMap.value.getOptions = dictSelect.childList;

  // 获取继承类型字典
  const inheritList = await sysDict({ field: "type", value: "inherit_type" });
  optionsMap.value.InheritOptions = inheritList.childList;

  // 获取排序类型字典
  const sortData = await sysDict({ field: "type", value: "sort_type" });
  optionsMap.value.sortTypeOptions = sortData.childList;

  // 获取是/否类型字典
  const isOrNotData = await sysDict({ field: "type", value: "is_or_not" });
  optionsMap.value.isOrNotOptions = isOrNotData.childList;

  // 获取菜单列表
  const menuData = await queryList('menu',{ type: 0 });
  optionsMap.value.menuList = menuData;
};

// 响应式变量，存储表格数据
const tableData = ref<any[]>([]);

// 动态生成 VXETable 的列配置
const generateColumns = (): VxeGridProps["columns"] => {
  // 遍历字段映射表，为每个字段生成列配置
  return Object.entries(fieldLabelMap).map(([field, title]) => {
    // 设置列的最小宽度
    let minWidth = 120;
    if (["title", "field"].includes(field)) minWidth = 150; // 显示名称和字段名列更宽
    if (["isTable", "isForm", "formRequire", "isSearch"].includes(field))
      minWidth = 100; // 布尔型字段列稍窄

    // 根据字段类型确定行内编辑的渲染器
    let editRender: any = null;
    // 简单输入框字段
    if (
      field === "title" ||
      field === "field" ||
      field === "width" ||
      field === "fieldLength" ||
      field === "sort" ||
      field === "tableAlias" ||
      field === "tableField" ||
      field === "searchValue" ||
      field === "selClassName" ||
      field === "selField"
    ) {
      editRender = { name: "input" };
    }
    // 字段类型下拉框
    else if (field === "fieldType") {
      editRender = {
        name: "$select",
        options: [
          { value: "varchar", label: "varchar" },
          { value: "int", label: "int" },
          { value: "bigint", label: "bigint" },
          { value: "decimal", label: "decimal" },
          { value: "datetime", label: "datetime" },
          { value: "text", label: "text" },
        ],
      };
    }
    // 表单类型下拉框
    else if (field === "formType") {
      editRender = {
        name: "$select",
        options: [
          { value: "input", label: "输入框" },
          { value: "textarea", label: "文本域" },
          { value: "select", label: "下拉框" },
          { value: "radio", label: "单选框" },
          { value: "checkbox", label: "复选框" },
          { value: "date", label: "日期" },
          { value: "upload", label: "上传" },
        ],
      };
    }
    // 是/否类型字段下拉框
    else if (
      [
        "isTable",
        "isForm",
        "isSearch",
        "formRequire",
        "exportExcel",
        "importExcel",
        "isSort",
        "isTableEdit",
        "isFormEdit",
        "isTotal",
        "isUnique",
      ].includes(field)
    ) {
      editRender = {
        name: "$select",
        options: [
          { value: "1", label: "是" },
          { value: "0", label: "否" },
        ],
      };
    }
    // 查询条件字段下拉框
    else if (field === "searchCondition") {
      editRender = {
        name: "$select",
        options: [
          { value: "eq", label: "=" },
          { value: "ne", label: "≠" },
          { value: "gt", label: ">" },
          { value: "ge", label: ">=" },
          { value: "lt", label: "<" },
          { value: "le", label: "<=" },
          { value: "like", label: "包含" },
          { value: "notlike", label: "不包含" },
        ],
      };
    }
    // 默认为输入框
    else {
      editRender = { name: "input" };
    }

    // 返回单个列的配置对象
    return {
      field, // 对应数据项的字段名
      title, // 列标题
      minWidth, // 最小宽度
      editRender, // 启用行内编辑及其渲染器
      slots: {
        // 自定义单元格内容，使用 formatCell 函数处理显示值
        default: ({ row }) => [formatCell(row[field], field)],
      },
    };
  });
};

// 定义操作列的配置
const operationColumn = {
  title: "操作", // 列标题
  fixed: "right", // 固定在右侧
  width: 160, // 列宽度
  slots: { default: "operate" }, // 使用名为 'operate' 的插槽渲染内容
};

// 定义第一个表格 (gridOptions1) 的完整配置，使用 reactive 包裹以支持响应式更新
const gridOptions1 = reactive<VxeGridProps>({
  border: true, // 显示边框
  size: "mini", // 小尺寸
  showOverflow: true, // 内容溢出时显示省略号
  data: tableData.value, // 绑定响应式表格数据
  columns: [...generateColumns(), operationColumn], // 合并动态生成的列和操作列
  toolbarConfig: {
    // 工具栏配置
    slots: { buttons: "toolbar_buttons" }, // 使用名为 'toolbar_buttons' 的插槽放置按钮
    refresh: true, // 显示刷新按钮
  },
  editConfig: {
    // 编辑配置
    trigger: "click", // 触发编辑的方式
    mode: "row", // 编辑模式：行编辑
    beforeEditMethod: () => true, // 控制哪些单元格可以编辑
  },
  // 定义编辑验证规则
  editRules: {
    title: [{ required: true, message: "显示名称不能为空" }],
    field: [{ required: true, message: "字段英文名称不能为空" }],
  },
  // 定义插槽，用于渲染操作列和工具栏按钮
  slots: {
    operate: "operate",
    toolbar_buttons: "toolbar_buttons",
  },
});

// 格式化单元格显示内容的函数
const formatCell = (value: any, field: string): string => {
  // 如果值为 null 或 undefined，显示 '-'
  if (value === null || value === undefined) return "-";
  // 需要特殊处理的布尔型字段
  const booleanFields = [
    "isTable",
    "isForm",
    "isSearch",
    "formRequire",
    "exportExcel",
    "importExcel",
    "isSort",
    "isTableEdit",
    "isFormEdit",
    "isTotal",
    "isUnique",
  ];
  // 如果是布尔型字段，'1' 显示为 '是'，其他值显示为 '否'
  if (booleanFields.includes(field)) return value === "1" ? "是" : "否";
  // 其他情况转换为字符串返回
  return String(value);
};

// 弹窗组件的引用，用于调用其方法
const fieldDialog = ref();

// 保存回调函数，处理弹窗保存后的数据
const onSave = (data: any) => {
  // 检查表格中是否已存在具有相同 id 的行
  const exists = tableData.value.find((item) => item.id === data.id);
  if (exists) {
    // 如果存在，则更新该行数据
    Object.assign(exists, data);
  } else {
    // 如果不存在，则将新数据添加到数组开头
    tableData.value.unshift(data);
  }
  // ✅ 更新 vxe-grid 数据引用（触发视图更新）
  gridOptions1.data = [...tableData.value];
};

// 监听 tableData 的变化，当数据变化时同步更新 gridOptions1 的 data
watch(
  tableData,
  (newVal) => {
    gridOptions1.data = newVal;
  },
  { deep: true } // 深度监听，确保内部属性变化也能触发
);

// 表单数据对象，使用 ref 包裹
const form = ref({
  id: "",
  formName: "",
  className: "",
  tableName: "",
  classPath: "",
  inherit: "",
  formType: "",
  isTotal: "",
  tableWidthAgv: "",
  pageLimits: 0,
  sortField: "",
  sortType: "",
  menuId: "",
  subTable: "",
  isCreateCode: "",
  hasAttment: "",
  attmentFormat: "",
});

// 定义新增行时使用的默认字段值
const defaultFieldValues = {
  title: "",
  field: "",
  width: 120,
  isTable: "1",
  isForm: "1",
  isSearch: "0",
  fieldType: "varchar",
  formType: "input",
  fieldLength: 255,
  formRequire: "0",
  exportExcel: "1",
  importExcel: "0",
  isSort: "0",
  dictType: "",
  isTableEdit: "0",
  isFormEdit: "0",
  isTotal: "0",
  sort: 0,
  tableAlias: "",
  tableField: "",
  searchCondition: "eq",
  searchValue: "",
  isUnique: "0",
  selClassName: "",
  selField: "",
};

// 处理继承类字段变化的函数
const handleInherit = async (value, formData) => {
  // 清空当前表格数据
  tableData.value = [];
  // 调用 API 获取基础字段
  const res = await getBaseField({ inheritType: value });
  // 如果返回数据无效，则直接返回
  if (!res || !Array.isArray(res)) return;

  // 将返回的字段数据映射为新的行数据
  const newRows = res.map((item) => ({
    ...defaultFieldValues, // 使用默认值
    title: item.name || item.field || "", // 显示名称
    field: item.field || "", // 字段英文名
    fieldType: item.type || "varchar", // 字段类型
    formType: item.formType || "input", // 表单类型
    fieldLength: item.length || 255, // 字段长度
    // 特殊处理：createTime 和 updateTime 字段默认不导出
    exportExcel: ["createTime", "updateTime"].includes(item.field) ? "0" : "1",
    id: Date.now() + Math.random(), // 生成唯一 id
  }));

  // 将新行数据添加到表格数据中
  tableData.value.push(...newRows);
  // 更新 gridOptions1 的数据引用
  gridOptions1.data = [...tableData.value];
};

// 表单配置：驱动整个表单结构
const formConfig = ref([
  {
    field: "formType", // 字段名
    label: "表单类型", // 标签文字
    component: "select", // 组件类型
    required: true, // 是否必填
    optionsKey: "getOptions", // 选项数据在 optionsMap 中的键名
    colSpan: 5, // 占据的栅格列数
  },
  {
    field: "formName",
    label: "表单名称",
    component: "input",
    required: true,
    colSpan: 5,
  },
  {
    field: "className",
    label: "类名称",
    component: "input",
    required: true,
    colSpan: 5,
  },
  {
    field: "tableName",
    label: "表名",
    component: "input",
    required: false,
    colSpan: 5,
  },
  {
    field: "classPath",
    label: "包路径",
    component: "input",
    required: true,
    colSpan: 5,
  },
  {
    field: "inherit",
    label: "继承类",
    component: "select",
    required: true,
    optionsKey: "InheritOptions",
    colSpan: 5,
    events: {
      // 绑定 change 事件
      change: handleInherit,
    },
  },
  {
    field: "isTotal",
    label: "开启合计",
    component: "select",
    required: true,
    optionsKey: "isOrNotOptions",
    colSpan: 5,
  },
  {
    field: "tableWidthAgv",
    label: "表宽等分",
    component: "select",
    required: true,
    optionsKey: "isOrNotOptions",
    colSpan: 5,
  },
  {
    field: "sortField",
    label: "初始化排序字段",
    component: "input",
    required: true,
    colSpan: 5,
  },
  {
    field: "sortType",
    label: "初始化排序类型",
    component: "select",
    required: true,
    optionsKey: "sortTypeOptions",
    colSpan: 5,
  },
  {
    field: "pageLimits",
    label: "分页行数",
    component: "input",
    required: false,
    colSpan: 5,
  },
  {
    field: "menuId",
    label: "上级菜单",
    component: "select",
    required: true,
    optionsKey: "menuList",
    props: { label: "title", value: "id" }, // el-option 映射字段
    colSpan: 5,
  },
  {
    field: "hasAttment",
    label: "附件上传",
    component: "select",
    required: false,
    optionsKey: "isOrNotOptions",
    colSpan: 5,
  },
  {
    field: "attmentFormat",
    label: "附件格式",
    component: "input",
    required: true,
    colSpan: 5,
  },
  {
    field: "isCreateCode",
    label: "生成代码",
    component: "select",
    required: false,
    optionsKey: "isOrNotOptions",
    colSpan: 5,
  },
  {
    field: "subTable",
    label: "是否分表",
    component: "select",
    required: false,
    optionsKey: "isOrNotOptions",
    colSpan: 5,
  },
]);

// 新增行函数
const addRow = () => {
  // 创建一个新行对象，使用默认值并生成唯一 id
  const newRow = {
    ...defaultFieldValues,
    id: Date.now() + Math.random(),
  };
  // 将新行插入到数组开头
  tableData.value.unshift(newRow);
  // 更新 gridOptions1 的数据引用
  gridOptions1.data = [...tableData.value];
};

// 删除行函数
const deleteRow = (row: any) => {
  // 查找指定行在数组中的索引
  const index = tableData.value.findIndex((item) => item.id === row.id);
  if (index !== -1) {
    // 如果找到，则从数组中移除该行
    tableData.value.splice(index, 1);
    // 更新 gridOptions1 的数据引用
    gridOptions1.data = [...tableData.value];
  }
};
const formId = route.query.id;
// 提交表单函数
const submitForm = async () => {
  // 构造要提交的数据对象
  let arr = {
    ...form.value,
    joinList: [], // 关联单据
    formList: [], // 下游单据
    childList: tableData.value.map(({ id, ...item }) => {
      const isRealId =
        (formId && typeof id === "number") ||
        (typeof id === "string" && /^\d+$/.test(id));

      return formId ? (isRealId ? { id, ...item } : item) : item;
    }),
  };

  // 如果没有 formId，说明是新增，绝对不能带任何前端生成的 id
  if (!formId) {
    const checked = await checkOnly('form',{
      fieldName: "className",
      fieldValue: form.value.className,
    });

    if (checked.code === 0) {
      const result = await formAdd(arr);
      console.log("提交数据:", arr);
      console.log("后端响应:", result);
      // 可在此处添加提示或跳转逻辑
    } else {
      ElMessage.error(checked.msg || "类名已存在");
    }
  } else {
    // 编辑模式：可以携带真实 id 提交
    const result = await formAdd(arr);
    console.log("提交数据（编辑）:", arr);
    console.log("后端响应:", result);
  }
};
// 返回
const goBack = ()=>{
  router.back()
}
// 根据 ID 加载表单数据的函数
const loadFormData = async (id: string) => {
  // 调用 API 获取详情
  const res = await getFormDetail({ id });
  // 将返回的数据赋值给 form
  form.value = res;
  // 将返回的子项列表赋值给 tableData
  tableData.value = res.childList || [];
};

// 组件挂载完成后执行
onMounted(() => {
  // 获取所有字典数据
  getDatas();
  // 如果 id 存在且为字符串
  if (formId && typeof formId === "string") {
    console.log("收到的 ID:", formId);
    // 加载该 id 对应的数据
    loadFormData(formId);
  }
});
// -----------------------
// 下游单据表格数据与配置
// -----------------------

const downTableData = ref<any[]>([]);

// 下游单据列配置
const generateDownColumns = (): VxeGridProps["columns"] => {
  return [
    { type: "seq", title: "序号", width: 50 },
    {
      field: "formName",
      title: "表单名称",
      minWidth: 160,
      editRender: { name: "input" },
    },
    {
      field: "className",
      title: "实体类名",
      minWidth: 140,
      editRender: { name: "input" },
    },
    {
      field: "foreignKeyName",
      title: "外键字段",
      minWidth: 140,
      editRender: { name: "input" },
    },
    {
      field: "isForm",
      title: "表单显示",
      minWidth: 100,
      editRender: {
        name: "$select",
        options: [
          { value: 1, label: "是" },
          { value: 0, label: "否" },
        ],
      },
      slots: {
        default: ({ row }) => [row.isForm === 1 ? "是" : "否"],
      },
    },
    {
      field: "checkDelete",
      title: "校验删除",
      minWidth: 100,
      editRender: {
        name: "$select",
        options: [
          { value: "1", label: "是" },
          { value: "0", label: "否" },
        ],
      },
      slots: {
        default: ({ row }) => [row.checkDelete === "1" ? "是" : "否"],
      },
    },
    {
      field: "checkEdit",
      title: "头部按钮",
      minWidth: 100,
      editRender: {
        name: "$select",
        options: [
          { value: "1", label: "是" },
          { value: "0", label: "否" },
        ],
      },
      slots: {
        default: ({ row }) => [row.checkEdit === "1" ? "是" : "否"],
      },
    },
    {
      field: "checkReCheck",
      title: "行按钮",
      minWidth: 100,
      editRender: {
        name: "$select",
        options: [
          { value: "1", label: "是" },
          { value: "0", label: "否" },
        ],
      },
      slots: {
        default: ({ row }) => [row.checkReCheck === "1" ? "是" : "否"],
      },
    },
    {
      field: "selClassName",
      title: "弹出选择类名",
      minWidth: 160,
      editRender: { name: "input" },
    },
    {
      field: "sort",
      title: "显示顺序",
      minWidth: 100,
      editRender: { name: "input" },
    },
    {
      title: "操作",
      width: 120,
      fixed: "right",
      slots: { default: "operate_down" },
    },
  ];
};

// 下游单据表格配置
const gridOptions2 = reactive<VxeGridProps>({
  border: true,
  size: "mini",
  showOverflow: true,
  data: downTableData.value,
  columns: generateDownColumns(),
  editConfig: {
    trigger: "click",
    mode: "row",
    beforeEditMethod: () => true,
  },
  toolbarConfig: {
    refresh: true,
  },
  slots: {
    operate_down: "operate_down",
  },
});

// 删除下游单据行
const deleteDownRow = (row: any) => {
  const index = downTableData.value.findIndex(
    (item) => item.downFormId === row.downFormId
  );
  if (index > -1) {
    downTableData.value.splice(index, 1);
    gridOptions2.data = [...downTableData.value];
  }
};

// 新增下游单据行
const addDownRow = () => {
  const newRow = {
    downFormId: null,
    formName: "",
    className: "",
    foreignKeyName: "",
    checkDelete: "0",
    checkEdit: "0",
    checkReCheck: "0",
    sort: 0,
    selClassName: "",
    isForm: 0,
    id: Date.now() + Math.random(), // 前端临时 id
  };
  downTableData.value.unshift(newRow);
  gridOptions2.data = [...downTableData.value];
};

// 监听数据变化
watch(
  downTableData,
  (newVal) => {
    gridOptions2.data = newVal;
  },
  { deep: true }
);

// -----------------------
// 关联单据表格数据与配置
// -----------------------

const joinTableData = ref<any[]>([]);

// 关联单据列配置
const generateJoinColumns = (): VxeGridProps["columns"] => {
  return [
    { type: "seq", title: "序号", width: 50 },
    {
      field: "tableName",
      title: "关联表名",
      minWidth: 180,
      editRender: { name: "input" },
    },
    {
      field: "tableAlias",
      title: "表别名",
      minWidth: 120,
      editRender: { name: "input" },
    },
    {
      field: "joinType",
      title: "关联模式",
      minWidth: 120,
      editRender: {
        name: "$select",
        options: [
          { value: "leftJoin", label: "左连接" },
          { value: "innerJoin", label: "内连接" },
          { value: "rightJoin", label: "右连接" },
        ],
      },
    },
    {
      field: "joinCondition",
      title: "关联条件",
      minWidth: 200,
      editRender: { name: "input" },
    },
    {
      field: "sort",
      title: "显示顺序",
      minWidth: 100,
      editRender: { name: "input" },
    },
    {
      title: "操作",
      width: 120,
      fixed: "right",
      slots: { default: "operate_join" },
    },
  ];
};

// 关联单据表格配置
const gridOptions3 = reactive<VxeGridProps>({
  border: true,
  size: "mini",
  showOverflow: true,
  data: joinTableData.value,
  columns: generateJoinColumns(),
  editConfig: {
    trigger: "click",
    mode: "row",
    beforeEditMethod: () => true,
  },
  toolbarConfig: {
    refresh: true,
  },
  slots: {
    operate_join: "operate_join",
  },
});

// 删除关联单据行
const deleteJoinRow = (row: any) => {
  const index = joinTableData.value.findIndex(
    (item) => item.joinFormId === row.joinFormId
  );
  if (index > -1) {
    joinTableData.value.splice(index, 1);
    gridOptions3.data = [...joinTableData.value];
  }
};

// 新增关联单据行
const addJoinRow = () => {
  const newRow = {
    joinFormId: null,
    tableName: "",
    tableAlias: "",
    joinType: "leftJoin",
    joinCondition: "",
    sort: 0,
    id: Date.now() + Math.random(),
  };
  joinTableData.value.unshift(newRow);
  gridOptions3.data = [...joinTableData.value];
};

// 监听数据变化
watch(
  joinTableData,
  (newVal) => {
    gridOptions3.data = newVal;
  },
  { deep: true }
);
</script>

<style scoped lang="scss">
.m-btm {
  margin-bottom: 14px;
}

.demo-tabs {
  margin-bottom: 68px;
}
.card-e {
  position: fixed;
  bottom: 0;
  z-index: 11;
  width: -webkit-fill-available;
  .submit-flex-e {
    display: flex;
    justify-content: flex-end;
  }
}
</style>

<!-- 为了支持行内编辑和新增行，我们需要添加以下插槽模板 -->
